package com.fanshuai.soring.boot.config;

import com.fanshuai.soring.boot.mvc.metrics.MetricsFilter;
import com.fanshuai.soring.boot.mvc.metrics.MetricsHandlerAdapter;
import com.fanshuai.soring.boot.mvc.metrics.MetricsHandlerMapping;
import com.fanshuai.soring.boot.mvc.metrics.MetricsOutput;
import com.google.common.collect.ImmutableList;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;

public class MetricsFilterConfig {

    @Bean
    public FilterRegistrationBean<MetricsFilter> metricsFilterFilterRegistrationBean() {
        FilterRegistrationBean<MetricsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new MetricsFilter());

        registrationBean.setUrlPatterns(ImmutableList.of("/*"));
        registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE - 1);
        return registrationBean;
    }

    @Bean
    public MetricsOutput metricsOutput() {
        return new MetricsOutput();
    }

    @Bean
    @ConditionalOnBean(MetricsOutput.class)
    public MetricsHandlerMapping metricsHandlerMapping(MetricsOutput output) {
        return new MetricsHandlerMapping(output);
    }

    @Bean
    public MetricsHandlerAdapter metricsHandlerAdapter() {
        return new MetricsHandlerAdapter();
    }
}
